<template>
    <view class="container">
      <view class="title">考试报名</view>
      
      <view v-if="!hasApprovedEnrollment" class="tip-card card">
        <text>您还没有通过的报名申请，无法报名考试</text>
        <button class="btn-primary" size="mini" @click="navigateTo('/pages/enrollment/apply/apply')">立即报名</button>
      </view>
      
      <block v-else>
        <view class="filter-container">
          <view class="filter-tabs">
            <view 
              class="filter-tab" 
              :class="{ active: activeTab === 'all' }" 
              @click="activeTab = 'all'"
            >
              全部考试
            </view>
            <view 
              class="filter-tab" 
              :class="{ active: activeTab === 'registered' }" 
              @click="activeTab = 'registered'"
            >
              已报名
            </view>
          </view>
          
          <picker 
            mode="selector" 
            :range="examTypeOptions" 
            range-key="label" 
            :value="examTypeIndex" 
            @change="handleExamTypeChange"
          >
            <view class="filter-item">
              <text>考试科目：</text>
              <text>{{ examTypeOptions[examTypeIndex].label }}</text>
            </view>
          </picker>
        </view>
        
        <view class="exam-list">
          <view v-if="filteredExams.length === 0" class="empty-tip">
            暂无符合条件的考试
          </view>
          
          <view 
            class="exam-item card" 
            v-for="(item, index) in filteredExams" 
            :key="index"
            @click="viewExamDetail(item)"
          >
            <view class="exam-header">
              <view class="exam-name">{{ item.name }}</view>
              <view class="exam-status" :class="getStatusClass(item.status)">
                {{ getStatusText(item.status) }}
              </view>
            </view>
            
            <view class="exam-info">
              <text class="exam-type">{{ getExamTypeText(item.exam_type) }}</text>
              <text class="exam-date">考试时间：{{ formatDate(item.exam_date) }}</text>
              <text class="exam-deadline">报名截止：{{ formatDate(item.registration_deadline) }}</text>
            </view>
            
            <view class="exam-detail">
              <text class="exam-applicants">已报名人数：{{ item.current_applicants }}/{{ item.max_applicants }}</text>
              <text class="exam-progress">剩余名额：{{ item.max_applicants - item.current_applicants }}</text>
            </view>
            
            <view class="exam-actions">
              <button 
                class="btn-register" 
                :disabled="!canRegister(item)"
                @click.stop="registerExam(item)"
              >
                {{ isRegistered(item) ? '已报名' : '立即报名' }}
              </button>
            </view>
          </view>
        </view>
      </block>
    </view>
  </template>
  
  <script>
  import { mapActions, mapGetters } from 'vuex';
  import { formatDate } from '@/utils/date';
  import config from '@/config/index';
  
  export default {
    data() {
      return {
        activeTab: 'all',
        examTypeOptions: [
          { value: '', label: '全部科目' },
          ...config.examSubjects
        ],
        examTypeIndex: 0
      };
    },
    computed: {
      ...mapGetters('enrollment', [
        'approvedEnrollments'
      ]),
      ...mapGetters('exam', [
        'examList',
        'myExams'
      ]),
      hasApprovedEnrollment() {
        return this.approvedEnrollments && this.approvedEnrollments.length > 0;
      },
      filteredExams() {
        let result = [...this.examList];
        
        // 考试科目筛选
        const examType = this.examTypeOptions[this.examTypeIndex].value;
        if (examType) {
          result = result.filter(item => item.exam_type === examType);
        }
        
        // 标签筛选
        if (this.activeTab === 'registered') {
          const registeredExamIds = this.myExams.map(item => item.exam_id);
          result = result.filter(item => registeredExamIds.includes(item.id));
        }
        
        return result;
      }
    },
    onLoad() {
      // 获取考试列表
      this.getExams();
      
      // 获取我的考试列表
      this.getMyExams();
    },
    methods: {
      ...mapActions('exam', [
        'getExams',
        'getMyExams',
        'registerExam',
        'cancelExamRegistration'
      ]),
      navigateTo(url) {
        uni.navigateTo({
          url
        });
      },
      formatDate(date) {
        return formatDate(date, 'YYYY-MM-DD HH:mm');
      },
      handleExamTypeChange(e) {
        this.examTypeIndex = e.detail.value;
      },
      getStatusText(status) {
        const statusMap = {
          'upcoming': '即将开始',
          'ongoing': '进行中',
          'completed': '已结束',
          'cancelled': '已取消'
        };
        return statusMap[status] || status;
      },
      getStatusClass(status) {
        const classMap = {
          'upcoming': 'status-upcoming',
          'ongoing': 'status-ongoing',
          'completed': 'status-completed',
          'cancelled': 'status-cancelled'
        };
        return classMap[status] || '';
      },
      getExamTypeText(type) {
        const examType = config.examSubjects.find(item => item.value === type);
        return examType ? examType.label : type;
      },
      isRegistered(exam) {
        return this.myExams.some(item => item.exam_id === exam.id && ['pending', 'approved'].includes(item.status));
      },
      canRegister(exam) {
        // 判断是否可以报名考试
        if (exam.status !== 'upcoming') {
          return false;
        }
        
        if (exam.current_applicants >= exam.max_applicants) {
          return false;
        }
        
        if (this.isRegistered(exam)) {
          return false;
        }
        
        // 判断是否超过报名截止日期
        const now = new Date();
        const deadline = new Date(exam.registration_deadline);
        if (now > deadline) {
          return false;
        }
        
        return true;
      },
      viewExamDetail(exam) {
        uni.navigateTo({
          url: `/pages/exam/schedule/schedule?id=${exam.id}`
        });
      },
      registerExam(exam) {
        if (!this.canRegister(exam)) return;
        
        this.showModal(`确认报名参加 ${exam.name} 吗？`)
          .then(confirm => {
            if (confirm) {
              uni.showLoading({
                title: '报名中...'
              });
              
              this.registerExam(exam.id)
                .then(() => {
                  this.showToast('报名成功', 'success');
                  // 重新获取考试列表和我的考试列表
                  this.getExams();
                  this.getMyExams();
                })
                .catch(err => {
                  this.showToast(err.message || '报名失败');
                })
                .finally(() => {
                  uni.hideLoading();
                });
            }
          });
      }
    }
  };
  </script>
  
  <style lang="scss">
  .container {
    padding: 30rpx;
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 40rpx;
  }
  
  .tip-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    margin-bottom: 30rpx;
  }
  
  .filter-container {
    margin-bottom: 30rpx;
  }
  
  .filter-tabs {
    display: flex;
    margin-bottom: 20rpx;
    border-bottom: 1px solid #eee;
  }
  
  .filter-tab {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 30rpx;
    color: #666;
  }
  
  .filter-tab.active {
    color: #3c8dbc;
    border-bottom: 2px solid #3c8dbc;
  }
  
  .filter-item {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    padding: 20rpx 0;
  }
  
  .exam-list {
    margin-bottom: 40rpx;
  }
  
  .empty-tip {
    text-align: center;
    padding: 60rpx 0;
    color: #999;
  }
  
  .exam-item {
    padding: 30rpx;
    margin-bottom: 20rpx;
  }
  
  .exam-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
  }
  
  .exam-name {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .exam-status {
    font-size: 24rpx;
    padding: 4rpx 16rpx;
    border-radius: 20rpx;
  }
  
  .status-upcoming {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  .status-ongoing {
    background-color: #fff7e6;
    color: #e6a23c;
  }
  
  .status-completed {
    background-color: #e6f7f0;
    color: #52c41a;
  }
  
  .status-cancelled {
    background-color: #fff3f3;
    color: #f56c6c;
  }
  
  .exam-info {
    display: flex;
    flex-direction: column;
    margin-bottom: 20rpx;
  }
  
  .exam-type {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 10rpx;
  }
  
  .exam-date, .exam-deadline {
    font-size: 26rpx;
    color: #999;
    margin-bottom: 6rpx;
  }
  
  .exam-detail {
    display: flex;
    justify-content: space-between;
    font-size: 26rpx;
    color: #666;
    margin-bottom: 20rpx;
  }
  
  .exam-actions {
    display: flex;
    justify-content: flex-end;
  }
  
  .btn-register {
    width: 200rpx;
    height: 70rpx;
    line-height: 70rpx;
    font-size: 28rpx;
    color: #fff;
    background-color: #3c8dbc;
    border-radius: 6rpx;
  }
  
  .btn-register[disabled] {
    background-color: #ddd;
    color: #999;
  }
  
  .btn-primary {
    color: #fff;
    background-color: #3c8dbc;
  }
  </style>